<?php

namespace apiend\models\searchs;

use yii\data\ActiveDataProvider;
use common\helpers\WordMatcher;
use common\helpers\Url;

/**
 * 统一搜索模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
abstract class UnifiedSearch extends \common\base\Model implements \common\db\SearchModelInterface {

    use \common\traits\Constants;
    use \common\traits\SearchForBuildQuery;

    const TYPE_PRODUCT = 'product';
    const TYPE_DYNAMIC = 'dynamic';
    const TYPE_GROUP = 'group';

    /**
     * @var string 操作内容类型
     */
    public $keyword;

    /**
     * @var string 操作内容类型
     */
    public $type;

    /**
     * @var string 操作内容类型
     */
    protected $searchModel = null;

    /**
     * @var string 操作内容类型
     */
    private $_words = [];

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['keyword', 'type'], 'required'],
            ['type', 'in', 'range' => static::getConstants('type'), 'message' => '{attribute}不正确'],
            [['type'], 'validateType'],
            [['keyword'], 'validateKeyword'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'keyword' => '关键词',
            'type' => '检索类型',
        ];
    }

    public function validateType($attribute) {
        if ($this->hasErrors()) {
            return;
        }
    }

    public function getModels() {
        $ids = $this->_pks;
        $models = [];
        if ($this->type == self::TYPE_PRODUCT) {
            $models = ShopFavorite::findAll([
                'user_id' => $this->user_id,
                'product_id' => $ids,
            ]);
        } elseif ($this->type == self::TYPE_DYNAMIC) {
            $models = DynamicFavorite::findAll([
                'user_id' => $this->user_id,
                'dynamic_id' => $ids,
            ]);
        }
        return $models;
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     * @return ActiveDataProvider
     */
    public function getWords() {
        $q = $this->keywords;

        if ($q) {
            $matcher = new WordMatcher();
            $matcher->match($q, $matched);

            if (!empty($matched)) {
                $kids = array_keys($matched);
                $query->joinWith('keywords key');
                $query->andFilterWhere(['key.lib_id' => $kids]);
            } else {
                $keywords = explode(' ', $q);
                if (!empty($keywords)) {
                    $likewhere = ['or'];
                    foreach ($keywords as $word) {
                        $likewhere[] = ['like', 't.name', $word];
                    }
                    $query->andFilterWhere($likewhere);
                }
            }
        }

        $dataProvider = new ActiveDataProvider([
            'query' => $query
        ]);

//        return \common\helpers\Debug::sql($query);

        return $dataProvider;
    }

    /**
     * 返回检索列表所需的内容
     * return array
     */
    public function fields() {
        return [
            'id',
            'name',
            'thumb' => function() {
                return Url::attach($this->cover);
            },
            'description',
            'price',
            'link' => function () {
                return Url::h5('/goods/' . $this->id);
            },
        ];
    }

}
